#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Flight策略演示脚本
展示韩国顶级交易员Flight的三大交易策略
"""

import os
import json
import time
from datetime import datetime
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

def demo_flight_strategy():
    """演示Flight策略"""
    print("🚀 Flight策略演示")
    print("=" * 60)
    print("韩国顶级交易员Flight的小资金高倍率交易系统")
    print("三大策略：高倍率播种 + 逆势刀锋 + 量价背离")
    print("=" * 60)
    
    try:
        # 导入Flight策略
        from flight_strategy import (
            init_flight_exchange, get_flight_ohlcv_data, analyze_with_flight,
            detect_volume_spike, identify_key_levels, detect_rsi_divergence,
            detect_volume_price_divergence, analyze_flight_market_state,
            FLIGHT_CONFIG
        )
        
        # 初始化交易所
        print("\n📡 初始化Flight交易所...")
        exchange = init_flight_exchange(use_demo=True)
        if exchange:
            print(f"✅ 交易所: {exchange.name}")
            print(f"✅ 沙盒模式: {getattr(exchange, 'sandbox', 'Unknown')}")
        
        # 显示Flight策略配置
        print(f"\n⚙️ Flight策略配置:")
        print(f"   杠杆倍数: {FLIGHT_CONFIG['leverage']}x")
        print(f"   仓位比例: {FLIGHT_CONFIG['position_size_ratio']*100:.1f}%")
        print(f"   每日限额: {FLIGHT_CONFIG['daily_trade_limit']}次")
        print(f"   同时持仓: {FLIGHT_CONFIG['max_concurrent_positions']}个")
        print(f"   止损比例: {FLIGHT_CONFIG['stop_loss_ratio']*100:.1f}%")
        print(f"   止盈比例: {FLIGHT_CONFIG['take_profit_ratio']*100:.1f}%")
        
        # 演示交易对
        symbols = ['BTC/USDT:USDT', 'ETH/USDT:USDT', 'SOL/USDT:USDT']
        
        for symbol in symbols:
            print(f"\n" + "="*60)
            print(f"🎯 分析 {symbol}")
            print("="*60)
            
            # 获取数据
            price_data = get_flight_ohlcv_data(symbol)
            if not price_data:
                print(f"❌ {symbol} 数据获取失败")
                continue
            
            print(f"📊 当前行情:")
            print(f"   价格: ${price_data['price']:,.2f}")
            print(f"   变化: {price_data['price_change']:+.2f}%")
            print(f"   时间: {price_data['timestamp']}")
            
            # 技术分析
            df = price_data['full_data']
            
            print(f"\n🔬 技术分析:")
            
            # 天量检测
            volume_analysis = detect_volume_spike(df)
            print(f"   天量检测: {'🔥 是' if volume_analysis.get('has_spike') else '❌ 否'}")
            if volume_analysis.get('has_spike'):
                print(f"   天量次数: {volume_analysis.get('spike_count', 0)}")
                print(f"   连续天量: {volume_analysis.get('consecutive_spikes', 0)}根")
                print(f"   成交量倍数: {volume_analysis.get('latest_volume_ratio', 1):.2f}x")
            
            # 关键位分析
            key_levels = identify_key_levels(df)
            print(f"   支撑位: ${key_levels.get('support', 0):.2f}")
            print(f"   阻力位: ${key_levels.get('resistance', 0):.2f}")
            if key_levels.get('nearest_level'):
                nearest = key_levels['nearest_level']
                print(f"   最近关键位: {nearest['name']} (${nearest['price']:.2f}, 距离{nearest['distance_pct']:.2f}%)")
            
            # RSI背离分析
            rsi_divergence = detect_rsi_divergence(df)
            rsi_status = []
            if rsi_divergence.get('bearish_divergence'):
                rsi_status.append("看跌背离📉")
            if rsi_divergence.get('bullish_divergence'):
                rsi_status.append("看涨背离📈")
            print(f"   RSI背离: {' + '.join(rsi_status) if rsi_status else '无背离'}")
            print(f"   RSI值: {rsi_divergence.get('rsi', 50):.1f}")
            
            # 量价背离分析
            volume_divergence = detect_volume_price_divergence(df)
            vp_status = []
            if volume_divergence.get('bearish_divergence'):
                vp_status.append("看跌背离📉")
            if volume_divergence.get('bullish_divergence'):
                vp_status.append("看涨背离📈")
            print(f"   量价背离: {' + '.join(vp_status) if vp_status else '无背离'}")
            
            # 市场状态分析
            market_state = analyze_flight_market_state(df)
            print(f"\n🌊 市场状态:")
            print(f"   短期趋势: {market_state.get('short_trend', 'N/A')}")
            print(f"   长期趋势: {market_state.get('long_trend', 'N/A')}")
            print(f"   RSI状态: {market_state.get('rsi_status', 'N/A')}")
            print(f"   MACD趋势: {market_state.get('macd_trend', 'N/A')}")
            print(f"   布林带位置: {market_state.get('bb_status', 'N/A')}")
            
            # Flight策略AI分析
            print(f"\n🧠 Flight策略AI分析...")
            signal_data = analyze_with_flight(price_data, symbol)
            
            # 信号显示
            signal_emoji = {
                'BUY': '📈',
                'SELL': '📉',
                'HOLD': '⏸'
            }.get(signal_data['signal'], '❓')
            
            confidence_emoji = {
                'HIGH': '🟢',
                'MEDIUM': '🟡',
                'LOW': '🔴'
            }.get(signal_data['confidence'], '⚪')
            
            strategy_emoji = {
                '播种': '🌱',
                '逆势刀锋': '⚔️',
                '背离': '🔄',
                '观望': '⏸'
            }.get(signal_data.get('strategy_used', '观望'), '❓')
            
            print(f"\n{signal_emoji} Flight策略信号:")
            print(f"   信号: {signal_data['signal']}")
            print(f"   策略: {strategy_emoji} {signal_data['strategy_used']}")
            print(f"   信心: {confidence_emoji} {signal_data['confidence']}")
            
            stop_loss = signal_data.get('stop_loss')
            take_profit = signal_data.get('take_profit')
            if stop_loss and take_profit:
                print(f"   止损: ${stop_loss:,.2f}")
                print(f"   止盈: ${take_profit:,.2f}")
                risk_reward = signal_data.get('risk_reward_ratio')
                if risk_reward:
                    print(f"   盈亏比: {risk_reward:.2f}")
            
            print(f"\n📝 分析理由:")
            reason = signal_data.get('reason', '无理由')
            # 分行显示长理由
            for i, line in enumerate(reason.split('。')):
                if line.strip():
                    print(f"   {i+1}. {line.strip()}。")
            
            entry_reason = signal_data.get('entry_reason', '无入场理由')
            if entry_reason and entry_reason != '无入场理由':
                print(f"\n🎯 入场理由: {entry_reason}")
            
            # 等待一下再分析下一个
            time.sleep(2)
        
        print(f"\n" + "="*60)
        print("🎉 Flight策略演示完成")
        print("="*60)
        print("✅ Flight策略系统运行正常")
        print("✅ 三大策略：高倍率播种、逆势刀锋、量价背离")
        print("✅ AI分析：DeepSeek集成")
        print("✅ 风险管理：严格止损止盈")
        print("✅ 多账号支持：策略路由机制")
        
        return True
        
    except Exception as e:
        print(f"❌ Flight策略演示失败: {e}")
        return False

def demo_multi_account_flight():
    """演示多账号Flight策略"""
    print(f"\n🔗 多账号Flight策略演示")
    print("=" * 60)
    
    try:
        # 读取配置
        with open('accounts_config.json', 'r', encoding='utf-8') as f:
            config = json.load(f)
        
        # 查找Flight策略账户
        flight_accounts = []
        for account_id, account_config in config['accounts'].items():
            if account_config.get('strategy') == 'flight' and account_config.get('enabled', False):
                flight_accounts.append((account_id, account_config))
        
        if not flight_accounts:
            print("❌ 未找到启用的Flight策略账户")
            return False
        
        print(f"✅ 找到 {len(flight_accounts)} 个Flight策略账户:")
        
        for account_id, account_config in flight_accounts:
            print(f"\n📋 账户信息:")
            print(f"   ID: {account_id}")
            print(f"   名称: {account_config['name']}")
            print(f"   策略: {account_config['strategy']}")
            print(f"   杠杆: {account_config['config']['leverage']}x")
            print(f"   仓位比例: {account_config['config']['position_size_ratio']*100:.1f}%")
            print(f"   交易对数量: {len(account_config['config']['symbols'])}")
            
            symbols = [s['symbol'] for s in account_config['config']['symbols']]
            print(f"   交易对: {', '.join(symbols)}")
        
        print(f"\n✅ 多账号Flight策略配置验证通过")
        return True
        
    except Exception as e:
        print(f"❌ 多账号演示失败: {e}")
        return False

def main():
    """主演示函数"""
    print("🎬 Flight策略完整演示")
    print(f"演示时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 80)
    
    # 执行演示
    demos = [
        ("Flight策略功能演示", demo_flight_strategy),
        ("多账号Flight策略演示", demo_multi_account_flight),
    ]
    
    passed_demos = 0
    total_demos = len(demos)
    
    for demo_name, demo_func in demos:
        try:
            print(f"\n🎪 {demo_name}...")
            if demo_func():
                passed_demos += 1
                print(f"✅ {demo_name} 成功")
            else:
                print(f"❌ {demo_name} 失败")
        except Exception as e:
            print(f"❌ {demo_name} 异常: {e}")
    
    # 演示总结
    print("\n" + "=" * 80)
    print("🎊 Flight策略演示总结")
    print("=" * 80)
    print(f"总演示数: {total_demos}")
    print(f"成功演示: {passed_demos}")
    print(f"失败演示: {total_demos - passed_demos}")
    print(f"成功率: {(passed_demos / total_demos) * 100:.1f}%")
    
    if passed_demos == total_demos:
        print("\n🎉 所有演示成功！Flight策略系统完全就绪")
        print("\n🚀 可以通过以下方式启动Flight策略:")
        print("   1. 单独运行: python flight_strategy.py")
        print("   2. 多账号运行: python multi_account_manager.py")
        print("   3. 配置管理: 编辑 accounts_config.json")
    else:
        print("\n⚠️ 部分演示失败，请检查Flight策略配置")
    
    print(f"\n📚 Flight策略文档:")
    print("   - flight_strategy.py: 核心策略实现")
    print("   - accounts_config.json: 多账号配置")
    print("   - test_flight_integration.py: 集成测试")
    print("   - demo_flight_strategy.py: 功能演示")

if __name__ == "__main__":
    main()
